from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt


def scorePlot(data):
    def form_clusters(x, k):
        """
        聚类
        """
        # k是划分出的簇的个数
        model = KMeans(n_clusters=k, init='random')
        model.fit(x)
        labels = model.labels_
        print(labels)
        # 计算轮廓系数
        sh_score = silhouette_score(x, labels)
        return sh_score


    # 给定不同的 k 值来调用函数，并记录返回的轮廓系数。
    sh_scores = []
    for i in range(1, 10):
        sh_score = form_clusters(data, i+1)
        sh_scores.append(sh_score)
        no_clusters = [i + 1 for i in range(1, 10)]

    # 绘制不同的 k 值时生成的轮廓系数图形。
    plt.figure(2)
    plt.plot(no_clusters, sh_scores)
    plt.title("Cluster Quality")
    plt.xlabel("No of clusters k")
    plt.ylabel("Silhouette Coefficient")
    plt.show()